<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{layout/base :: html(
        title='新增回收站点',
        extraStyles=~{::styles},
        extraScripts=~{::scripts},
        content=~{::content}
      )}">
<head>
    <th:block th:fragment="styles">
        <style>
            #map-container {
                height: 400px;
                margin-bottom: 20px;
            }
            .required:after {
                content: " *";
                color: red;
            }
            .location-button {
                position: absolute;
                top: 10px;
                right: 10px;
                z-index: 1000;
            }
        </style>
    </th:block>
</head>
<body>
    <th:block th:fragment="content">
        <div class="container mt-4">
            <h2>新增回收站点</h2>
            <form id="stationForm" class="needs-validation" novalidate>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="name" class="form-label required">站点名称</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="address" class="form-label required">详细地址</label>
                            <input type="text" class="form-control" id="address" name="address" required>
                        </div>
                        <div class="mb-3">
                            <label for="contactPhone" class="form-label required">联系电话</label>
                            <input type="tel" class="form-control" id="contactPhone" name="contactPhone" required>
                        </div>
                        <div class="mb-3">
                            <label for="businessHours" class="form-label">营业时间</label>
                            <input type="text" class="form-control" id="businessHours" name="businessHours" 
                                   placeholder="例如: 09:00-18:00">
                        </div>
                        <div class="mb-3">
                            <label for="acceptableItems" class="form-label">可回收物品</label>
                            <textarea class="form-control" id="acceptableItems" name="acceptableItems" 
                                    rows="3" placeholder="请列出该站点可接收的回收物品类型"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">站点描述</label>
                            <textarea class="form-control" id="description" name="description" 
                                    rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="status" name="status" value="1" checked>
                                <label class="form-check-label" for="status">
                                    站点开放
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label required">选择站点位置</label>
                            <div style="position: relative;">
                                <div id="map-container"></div>
                                <button type="button" class="btn btn-primary location-button" onclick="getCurrentLocation()">
                                    <i class="fas fa-location-arrow"></i> 定位
                                </button>
                            </div>
                            <input type="hidden" id="latitude" name="latitude" required>
                            <input type="hidden" id="longitude" name="longitude" required>
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <a th:href="@{/stations}" class="btn btn-secondary ms-2">返回</a>
                </div>
            </form>
        </div>
    </th:block>

    <th:block th:fragment="scripts">
        <script type="text/javascript" src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=mNFuffn83uuKvzWesj3uqfVho6CVP9LI"></script>
        <script>
            var map;
            var geolocation;
            var defaultPoint;
            
            // 等待API加载完成
            function initBaiduMap() {
                if (typeof BMapGL === 'undefined') {
                    setTimeout(initBaiduMap, 100);
                    return;
                }
                
                map = new BMapGL.Map("map-container");
                geolocation = new BMapGL.Geolocation();
                defaultPoint = new BMapGL.Point(116.404, 39.915); // 默认北京市中心
                
                // 初始化地图
                function initMap(point) {
                    map.centerAndZoom(point, 15);
                    map.enableScrollWheelZoom();
                    map.addControl(new BMapGL.NavigationControl());
                    map.addControl(new BMapGL.ScaleControl());
                    
                    // 添加标记
                    map.clearOverlays();
                    var marker = new BMapGL.Marker(point);
                    map.addOverlay(marker);
                    updateLatLng(point);
                    
                    // 解析地址
                    var gc = new BMapGL.Geocoder();
                    gc.getLocation(point, function(rs) {
                        var addComp = rs.addressComponents;
                        var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                        document.getElementById('address').value = address;
                    });
                }
                
                // 获取当前位置
                function getCurrentLocation() {
                    geolocation.getCurrentPosition(function(r) {
                        if(this.getStatus() == BMAP_STATUS_SUCCESS) {
                            var point = new BMapGL.Point(r.point.lng, r.point.lat);
                            initMap(point);
                        } else {
                            alert('定位失败，请手动选择位置');
                            initMap(defaultPoint);
                        }
                    }, {
                        enableHighAccuracy: true,
                        timeout: 5000,
                        maximumAge: 0
                    });
                }
                
                // 页面加载时获取位置
                getCurrentLocation();
                
                // 点击地图更新标记位置
                map.addEventListener("click", function(e) {
                    var newPoint = new BMapGL.Point(e.point.lng, e.point.lat);
                    initMap(newPoint);
                });
            }

            // 页面加载完成后初始化地图
            document.addEventListener('DOMContentLoaded', initBaiduMap);
            
            // 更新经纬度输入框
            function updateLatLng(point) {
                document.getElementById('latitude').value = point.lat;
                document.getElementById('longitude').value = point.lng;
            }

            // 表单提交处理
            document.getElementById('stationForm').addEventListener('submit', function(event) {
                event.preventDefault();
                
                if (!this.checkValidity()) {
                    event.stopPropagation();
                    this.classList.add('was-validated');
                    return;
                }

                // 收集表单数据
                const formData = {
                    name: document.getElementById('name').value,
                    address: document.getElementById('address').value,
                    contactPhone: document.getElementById('contactPhone').value,
                    businessHours: document.getElementById('businessHours').value,
                    acceptableItems: document.getElementById('acceptableItems').value,
                    description: document.getElementById('description').value,
                    latitude: parseFloat(document.getElementById('latitude').value),
                    longitude: parseFloat(document.getElementById('longitude').value),
                    status: document.getElementById('status').checked ? 1 : 0
                };

                // 发送 AJAX 请求
                fetch('/stations', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                })
                .then(response => {
                    if (response.ok) {
                        window.location.href = '/stations';
                    } else {
                        return response.text().then(text => {
                            throw new Error(text || '保存失败');
                        });
                    }
                })
                .catch(error => {
                    alert(error.message);
                });
            });
        </script>
    </th:block>
</body>
</html> 